package com.feinno.urcs.group.siptask;

import com.feinno.urcs.dns.EnumService;
import com.feinno.urcs.group.api.GroupService;
import com.feinno.urcs.group.api.GroupTerminalService;
import com.feinno.urcs.group.entity.GroupIndex;
import com.feinno.urcs.group.entity.GroupInfo;
import com.feinno.urcs.group.entity.GroupMember;
import com.feinno.urcs.group.siptask.task.GroupByeArgs;
import com.feinno.urcs.group.siptask.task.GroupTaskEvents;
import com.feinno.urcs.mobile.UserLocatorService;
import com.feinno.urcs.mobile.entity.UserType;
import com.feinno.urcs.types.MobileNo;
import org.helium.framework.annotations.ServiceSetter;
import org.helium.framework.annotations.TaskEvent;
import org.helium.framework.annotations.TaskImplementation;
import org.helium.framework.task.Task;
import org.helium.framework.task.TaskProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sip.address.SipURI;
import java.util.List;

/**
 * 这个地方其实不需要DedicatedTask 了. 因为离线的逻辑是依靠了原来T端SessionMode 的消息dialog 的逻辑.Invite 也是走原来T端逻辑了.
 *
 * @author Li.Hongbo <lihongbo@feinno.com>
 */
@TaskImplementation(event = GroupTaskEvents.UNREG_BYE)
public class UnRegGroupByeTask implements Task<MobileNo> {

	private static final Logger LOGGER = LoggerFactory.getLogger(UnRegGroupByeTask.class);
	@ServiceSetter
	private GroupTerminalService groupTerminalService;
	@ServiceSetter
	private EnumService enumService;
	@ServiceSetter
	private UserLocatorService userLocatorService;
	@ServiceSetter
	private GroupService groupService;
	@TaskEvent(GroupTaskEvents.GROUP_BYE)
	private TaskProducer<GroupByeArgs> outterByeTask;

	@Override
	public void processTask(MobileNo mobileNo) {

		LOGGER.info("UnRegGroupByeTask.processTask , args :{}", mobileNo);
		try {


			SipURI uri = (SipURI) enumService.getSipURI(mobileNo);
			if (uri == null) {
				LOGGER.error(String.format("unReg   uri is null  MobileNo=%s ", mobileNo));
				return;
			}
			boolean isLocal = userLocatorService.lookup(mobileNo).getType().equals(UserType.INNER);

			List<Integer> groupList = groupService.getGroupList(mobileNo);
			for (int groupId : groupList) {

				// 如果群已经不存在, 则直接返回.
				// TODO  需要给发一个bye .但是前提是得存在dialog, 如果dialog 不存在就不用管了 .
				GroupByeArgs args = new GroupByeArgs();
				args.setGroupId(groupId);
				args.setCause(408);
				args.setToMember(mobileNo);
				args.setText("Request Timeout");

				if (isLocal) {
					groupTerminalService.silenced(args);
				} else {
					// TODO 外域逻辑
					outterByeTask.produce(args);
				}
			}
		} catch (Exception e) {
			LOGGER.error("getGrouplist error : {}", e);
		}
	}
}
